const app = getApp()

Page({
  data: {
    loading: true,
    dashboardData: {},
    progressList: [],
    
    // 筛选条件
    filterDate: '',
    planIndex: 0,
    processIndex: 0,
    userIndex: 0,
    
    // 筛选选项
    planOptions: [{ id: '', name: '全部计划' }],
    processOptions: [{ id: '', name: '全部工序' }],
    userOptions: [{ id: '', name: '全部员工' }],
    
    // 当前筛选参数
    currentFilters: {
      order_id: '',
      plan_id: '',
      process_id: '',
      user_id: ''
    }
  },

  onLoad(options) {
    this.initPage()
  },

  onShow() {
    this.loadDashboardData()
  },

  onPullDownRefresh() {
    this.loadDashboardData()
  },

  // 初始化页面
  initPage() {
    this.loadFilterOptions()
    this.loadDashboardData()
  },

  // 加载筛选选项
  loadFilterOptions() {
    // 加载生产计划选项
    app.request({
      url: '/getProductionPlans',
      method: 'GET',
      data: { limit: 100 }
    }).then(res => {
      if (res.code === 1) {
        const plans = [{ id: '', name: '全部计划' }]
        if (res.data.rows && res.data.rows.length > 0) {
          res.data.rows.forEach(plan => {
            plans.push({
              id: plan.id,
              name: plan.plan_name || plan.name
            })
          })
        }
        this.setData({ planOptions: plans })
      }
    }).catch(err => {
      console.error('加载生产计划选项失败:', err)
    })

    // 加载工序选项
    app.request({
      url: '/getProcessList',
      method: 'GET',
      data: { limit: 100 }
    }).then(res => {
      if (res.code === 1) {
        const processes = [{ id: '', name: '全部工序' }]
        if (res.data.list && res.data.list.length > 0) {
          res.data.list.forEach(process => {
            processes.push({
              id: process.id,
              name: process.name
            })
          })
        }
        this.setData({ processOptions: processes })
        console.log('工序选项加载成功:', processes)
      }
    }).catch(err => {
      console.error('加载工序选项失败:', err)
    })

    // 加载员工选项
    app.request({
      url: '/getUserList',
      method: 'GET',
      data: { limit: 100 }
    }).then(res => {
      if (res.code === 1) {
        const users = [{ id: '', name: '全部员工' }]
        if (res.data.list && res.data.list.length > 0) {
          res.data.list.forEach(user => {
            users.push({
              id: user.id,
              name: user.nickname || user.username
            })
          })
        }
        this.setData({ userOptions: users })
        console.log('员工选项加载成功:', users)
      }
    }).catch(err => {
      console.error('加载员工选项失败:', err)
    })
  },

  // 加载仪表板数据
  loadDashboardData() {
    this.setData({ loading: true })
    
    const params = {
      ...this.data.currentFilters
    }
    
    // 如果有日期筛选，转换为时间戳范围
    if (this.data.filterDate) {
      const startTime = new Date(this.data.filterDate + ' 00:00:00').getTime() / 1000
      const endTime = new Date(this.data.filterDate + ' 23:59:59').getTime() / 1000
      params.start_time = startTime
      params.end_time = endTime
    }

    // 调试信息
    console.log('筛选参数:', params)
    
    app.request({
      url: '/getProductionPlanProgress',
      method: 'GET',
      data: params
    }).then(res => {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
      
      if (res.code === 1) {
        // 直接使用后端返回的数据
        const overallStats = res.data.overallStats || {}
        const plans = res.data.plans || []
        
        // 确保数据完整性
        const dashboardData = {
          total_orders: overallStats.total_orders || 0,
          total_plans: overallStats.total_plans || plans.length,
          total_allocations: overallStats.total_allocations || 0,
          total_quantity: overallStats.total_quantity || 0,
          completed_quantity: overallStats.completed_quantity || 0,
          overall_completion_rate: overallStats.overall_completion_rate || 0
        }
        
        // 处理计划列表数据，确保字段映射正确
        const progressList = plans.map(plan => {
          return {
            id: plan.id,
            plan_name: plan.plan_name,
            name: plan.plan_name,
            order_no: plan.order ? (plan.order.order_no || '-') : '-',
            order_name: plan.order ? (plan.order.order_name || '-') : '-',
            product_name: plan.product_name || (plan.product ? plan.product.name : '-'),
            model_name: plan.product_model || (plan.model ? plan.model.name : '-'),
            total_quantity: plan.total_quantity || 0,
            completed_quantity: plan.actual_quantity || 0,
            completion_rate: plan.completion_rate || 0,
            status: plan.status || 0
          }
        })
        
        // 调试信息
        console.log('原始API响应:', res.data)
        console.log('仪表板数据:', dashboardData)
        console.log('进度列表:', progressList)
        console.log('第一个计划详情:', progressList[0])
        
        this.setData({
          dashboardData: dashboardData,
          progressList: progressList
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      this.setData({ loading: false })
      wx.stopPullDownRefresh()
      console.error('加载仪表板数据失败:', err)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    })
  },

  // 日期选择
  onDateChange(e) {
    this.setData({
      filterDate: e.detail.value
    })
  },

  // 生产计划选择
  onPlanChange(e) {
    const index = e.detail.value
    const planId = this.data.planOptions[index].id
    this.setData({
      planIndex: index,
      'currentFilters.plan_id': planId
    })
  },

  // 工序选择
  onProcessChange(e) {
    const index = e.detail.value
    const processId = this.data.processOptions[index].id
    console.log('选择工序:', index, processId, this.data.processOptions[index])
    this.setData({
      processIndex: index,
      'currentFilters.process_id': processId
    })
  },

  // 员工选择
  onUserChange(e) {
    const index = e.detail.value
    const userId = this.data.userOptions[index].id
    console.log('选择员工:', index, userId, this.data.userOptions[index])
    this.setData({
      userIndex: index,
      'currentFilters.user_id': userId
    })
  },

  // 应用筛选
  applyFilter() {
    this.loadDashboardData()
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      filterDate: '',
      planIndex: 0,
      processIndex: 0,
      userIndex: 0,
      currentFilters: {
        order_id: '',
        plan_id: '',
        process_id: '',
        user_id: ''
      }
    })
    this.loadDashboardData()
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      0: '未开始',
      1: '进行中', 
      2: '已暂停',
      3: '已完成'
    }
    return statusMap[status] || '未知'
  },

  // 获取状态颜色
  getStatusColor(status) {
    const colorMap = {
      0: '#999999', // 未开始 - 灰色
      1: '#07c160', // 进行中 - 绿色
      2: '#ff9500', // 已暂停 - 橙色
      3: '#1989fa'  // 已完成 - 蓝色
    }
    return colorMap[status] || '#999999'
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '-'
    const date = new Date(timestamp * 1000)
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString()
  },

  // 查看计划详细进度
  viewPlanProgress(e) {
    const planId = e.currentTarget.dataset.id
    if (!planId) {
      wx.showToast({
        title: '计划ID无效',
        icon: 'none'
      })
      return
    }
    
    wx.navigateTo({
      url: `/pages/production-plan-progress/production-plan-progress?planId=${planId}`
    })
  }
})
